package com.shop.shoporder.wapController;

import com.shop.shoporder.common.*;
import com.shop.shoporder.entity.order.Area;
import com.shop.shoporder.entity.order.UserAddress;
import com.shop.shoporder.service.AreaService;
import com.shop.shoporder.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = "*",maxAge = 3600)
@Controller
@RequestMapping("/wap")
public class WapUserAddressController {

    @Autowired
    AreaService areaService;

    @Autowired
    UserAddressService userAddressService;
    /**
     * 查询用户地址的省市区三级
     * @param request 市的ID和县级ID
     * @return
     */
    @PassToken
    @ResponseBody
    @RequestMapping("/getArea")
    public Response getArea(HttpServletRequest request){
        Integer parentId= InterfaceVer.VerNumber(request.getParameter("parentId"));
        Integer level= InterfaceVer.VerNumber(request.getParameter("level"));
//        int ids=0;
//        if(parentId.isEmpty()){
//           return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT,null,0,"",request);
//        }
//        ids=Integer.parseInt(id);
        List<Area> areaList=null;
        try {
            areaList=areaService.selectAreaList(parentId,level);
            if(areaList!=null&&areaList.size()!=0){
                return new Response(MessageConstants.MSG_SUCCESS,areaList,areaList.size(),"获取数据成功",request);
            }else{
                return new Response(MessageConstants.MSG_SUCCESS,areaList,areaList.size(),"获取数据失败",request);
            }

        }catch (Exception e){
            e.printStackTrace();
           return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"",request);
        }


    }

    /**
     * 地址ID
     * @param request
     * @return
     */
    @UserLoginToken
    @ResponseBody
    @Transactional
    @RequestMapping(value = "/addOrEditAddress",method = RequestMethod.POST)
    public Response addOrEditAddress(HttpServletRequest request){
        int id=0;try {id= InterfaceVer.VerNumber(request.getParameter("id"));}catch (Exception E){}
        int provinceId= InterfaceVer.VerNumber(request.getParameter("provinceId"));
        int cityId= InterfaceVer.VerNumber(request.getParameter("cityId"));
        int areaId= InterfaceVer.VerNumber(request.getParameter("areaId"));
        int userNoId= InterfaceVer.VerNumber(request.getParameter("userNoId"));
        String name=request.getParameter("name");
        String phone=request.getParameter("phone");
        String detailAddress=request.getParameter("detailAddress");
        int isDefault= InterfaceVer.VerNumber(request.getParameter("isDefault"));
        //System.out.println(provinceId+" "+cityId+" "+areaId+" "+name+" "+phone+" "+detailAddress+" "+isDefault);
        if(provinceId==0||cityId==0||areaId==0|| !OtherConstants.RegexpPhone(phone)){
            return new Response(MessageConstants.MSG_ILLEGAL_ARGUMENT,null,0,"",request);
        }
        UserAddress userAddress=null;
        if(id!=0){//地址ID不为0，则修改地址
            try {
                userAddress=userAddressService.selectByPrimaryKey(id);
                userAddress.setProvinceId(provinceId);
                userAddress.setCityId(cityId);
                userAddress.setAreaId(areaId);
                userAddress.setDetailAddr(detailAddress);
                userAddress.setName(name);
                userAddress.setPhone(phone);
                userAddress.setUserNoId(userNoId);
                userAddress.setIsdefault(isDefault);
                if (isDefault == 1) {
                    int res= userAddressService.updateAddressStateByUserId(userNoId);
                    if(res<=0){
                         throw new RuntimeException();
                    }
                }
                int row1=userAddressService.updateByPrimaryKeySelective(userAddress);
                if(row1>0){
//                    UserAddress userAddress1=userAddressService.getAddressAll(userAddress);
                    return new Response(MessageConstants.MSG_SUCCESS,userAddress,0,"更新成功",request);
                }else{
                    throw new RuntimeException();
                    //return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"",request);
                }
            }catch (Exception e){
                e.printStackTrace();
                return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"更新失败",request);
            }
        }else{//地址ID为0，则增加地址
            userAddress=new UserAddress();
            try{
                userAddress.setProvinceId(provinceId);
                userAddress.setCityId(cityId);
                userAddress.setAreaId(areaId);
                userAddress.setDetailAddr(detailAddress);
                userAddress.setName(name);
                userAddress.setPhone(phone);
                userAddress.setUserNoId(userNoId);
                userAddress.setIsdefault(isDefault);
                if (isDefault == 1) {

                    UserAddress userAddress1 = userAddressService.getAddressDefault(userNoId);//查找会员是否有默认地址
                    if (userAddress1 != null) {
                        int res = userAddressService.updateAddressStateByUserId(userNoId);//如果有则取消
                        if (res <= 0) {
                            throw new RuntimeException();
                        }
                    }
                }
               int row2= userAddressService.insertSelective(userAddress);
                if(row2>0){
//                    UserAddress userAddress1=userAddressService.getAddressAll(userAddress);
                    return new Response(MessageConstants.MSG_SUCCESS,userAddress,0,"",request);
                }else{
                    throw new RuntimeException();
                    //return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"",request);
                }

            }catch (Exception e){
                e.printStackTrace();
                return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"",request);
            }
        }
    }


    /**
     * 获取用户地址列表
     * @param request
     * @return
     */
    @UserLoginToken
    @ResponseBody
    @RequestMapping("/getAddressList")
    public Response getAddressList(HttpServletRequest request){
            String userNoId=request.getParameter("userNoId");
        List<UserAddress> userAddressList=new ArrayList<>();
            if(userNoId.isEmpty()){
                return new Response(MessageConstants.MSG_SUCCESS,userAddressList,0,"",request);
            }
            int userNoIds=0;
           userNoIds= Integer.parseInt(userNoId);

           try {

              userAddressList= userAddressService.getAddressList(userNoIds);
              if(userAddressList!=null&&userAddressList.size()!=0){
                  for (UserAddress userAddress: userAddressList) {
                      userAddress.setProvinceId(null);
                      userAddress.setCityId(null);
                      userAddress.setAreaId(null);
                  }
                  return new Response(MessageConstants.MSG_SUCCESS,userAddressList,userAddressList.size(),"",request);
              }else{
                  return new Response(MessageConstants.MSG_SUCCESS,userAddressList,0,"",request);
              }

           }catch (Exception e){
               e.printStackTrace();
               return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"",request);
           }
    }

    /**
     * 获取用户地址列表
     * @param request
     * @return
     */
    @UserLoginToken
    @ResponseBody
    @RequestMapping("/getAddress")
    public Response getAddress(HttpServletRequest request){
        String addressId1=request.getParameter("addressId");
        String userNoId=request.getParameter("userNoId");
        UserAddress userAddres= new UserAddress();
        if(addressId1.isEmpty()){
            return new Response(MessageConstants.MSG_SUCCESS,userAddres,0,"",request);
        }
        int addressId=0;
        try {
            addressId= Integer.parseInt(addressId1);
        }catch (Exception e){}
        try {
            UserAddress userAddress1=new UserAddress();
            userAddress1.setUserNoId(InterfaceVer.VerNumber(userNoId));
            userAddress1.setId(addressId);
            userAddres= userAddressService.getAddressAll(userAddress1);
            if(userAddres!=null){
                if((userAddres.getUserNoId()==null?0:userAddres.getUserNoId())== InterfaceVer.VerNumber(userNoId)) {
//                    userAddres.setProvinceId(null);
//                    userAddres.setCityId(null);
//                    userAddres.setAreaId(null);
                    return new Response(MessageConstants.MSG_SUCCESS, userAddres, 1, "", request);
                }else {
                    return new Response(MessageConstants.MSG_SUCCESS,new UserAddress(),0,"",request);
                }
            }else{
                return new Response(MessageConstants.MSG_SUCCESS,new UserAddress(),0,"",request);
            }

        }catch (Exception e){
            e.printStackTrace();
            return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"",request);
        }
    }


@UserLoginToken
@ResponseBody
@RequestMapping("/deleteAddress")
public  Response deleteAddress(HttpServletRequest request){
        int addressId= InterfaceVer.VerNumber(request.getParameter("addressId"));
        int userNoId= InterfaceVer.VerNumber(request.getParameter("userNoId"));
        try{
            UserAddress userAddress=userAddressService.selectByPrimaryKey(addressId);
            if(userAddress!=null){
                if((userAddress.getUserNoId()==null?-1:userAddress.getUserNoId())!=userNoId){
                    return new Response(MessageConstants.MSG_DELETE_FAILED,null,0,"删除失败!",request);
                }
                if((userAddress.getIsdefault()==null?0:userAddress.getUserNoId())==1){
                    return new Response(MessageConstants.MSG_DELETE_FAILED,null,0,"默认地址不允许删除!",request);
                }
            }
            int row=userAddressService.updateIsDelete(addressId);
            if(row>0){
                return new Response(MessageConstants.MSG_SUCCESS,row,0,"删除成功",request);
            }else{
                return new Response(MessageConstants.MSG_DELETE_FAILED,null,0,"删除失败!",request);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Response(MessageConstants.MSG_SYS_ERROR,null,0,"删除失败!",request);
        }
}
    @UserLoginToken
    @ResponseBody
    @RequestMapping("/getDefaultAddress")
    public Response getDefaultAddress(HttpServletRequest request){
        int userNoId= InterfaceVer.VerNumber(request.getParameter("userNoId"));
        try {
            UserAddress userAddress1=userAddressService.getAddressDefault(userNoId);
            return new Response(MessageConstants.MSG_SUCCESS,userAddress1,0,"获取数据成功!",request);
        }catch (Exception e){
            e.printStackTrace();
            return new Response(MessageConstants.MSG_SYS_ERROR,new UserAddress(),0,"获取数据失败!",request);
        }
    }

}
